2016-07-04 4 views
3

여러 텍스트 필드의 유효성을 검사해야하지만 제대로 표시 할 수없는 함수가 있습니다. 예를 들어 $("#textfield").blur(validation);을 사용하여 각 필드가 포커스를 잃을 때 유효성 검사 기능을 실행합니다 (세 필드 모두 blur을 사용하여 유효성 검사 함수를 호출 함). 나는 if 문을 올바르게 주문하지 않는다고 생각합니다. 또한, this을 사용하여 유효성 검증을 수행하는 간단한 방법을 알고 있다면 그 또한 우수합니다. 고맙습니다.js의 단일 함수에서 여러 필드의 유효성을 검사하는 방법

function validation(height,width,color){ 

if (height.length == 0 || height == null){ //check for empty field 
    $("#msg").html("This field cannot be empty"); 
} 
else if (isNaN(height)){ //check that height is a number 
    $("#msg").html("The height must be a number"); 
}else{ 
    $("#msg").html("The height is " + height); //if height is ok shows this message 
} 
if (width.length == 0 || width== null){ //same for width 
    $("#msg").html("This field cannot be empty"); 
} 
else if (isNaN(width)){ 
    $("#msg").html("The width must be a number"); 
}else{ 
    $("#msg").html("The width is " + width); 
} 
if (color.length == 0 || color == null){ 
    $("#msg").html("This field cannot be empty"); 
} 
else if (color == "white" || color == "grey"){ //check that color is one of these two options 
    $("#msg").html("The color is " + color); 
}else{ 
    $("#msg").html("The color must be white or grey"); 
} 

} 
+0

이 작업에 단순히 부트 스트랩 라이브러리를 사용할 수 있습니다. – Saini

+0

HTML5 양식 유효성 검사가 도움이됩니까? 스크립트를 사용할 필요가 없습니다. [this] (https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Forms/Data_form_validation)을 시도하십시오. – Doug

+0

@Doug 문제는 제가 시험을 위해 공부하고 있다는 것입니다. 나는 이것을 이렇게 할 필요가 있습니다. 감사합니다. – Gonzalo

답변

1

당신이 재사용 isNullOrEmpty 기능을 만들 수있는 적어도 첫번째 .length === 0

다음에 null를 확인하는 것이 좋습니다 -

- 그럼 당신은 같이 일반화 할 수

function isNullOrEmpty (obj) { 
     return !((obj !== undefined) && (obj !== null) && (obj .length === 0)); 
    } 

function validateNumber(obj ,fieldName) { 
    if(isNaN(obj)) { 
     return 'The ' + fieldName + ' must be number.' 
    } 
    return ''; 
} 
+0

isNaN?에서 여러 변수를 평가할 수 있습니까? 'isNaN (obj1, obj2, obj3)' – Gonzalo

+0

과 같이 직접 입력하지는 않습니다. http://stackoverflow.com/a/28145281/213469 –

1

if(!height) { $("#msg").text("Height is not defined") } 이것은 거짓, 정의되지 않음, NaN, 0 및 문자열 빈 값의 약자입니다.

관련 문제