2016-07-04 5 views
3

複数のテキストフィールドを検証する必要があるが正しいとは思えない関数があります。たとえば、$("#textfield").blur(validation);を使用して、各フィールドがフォーカスを失ったときに検証関数を実行します(3つのフィールドすべてがblurを使用して検証関数を呼び出します)。私はifステートメントを正しく注文していないと思う。また、thisを使用して検証を行う簡単な方法がわかっている場合は、それも素晴らしいでしょう。ありがとうございました。jsの1つの関数で複数のフィールドを検証する方法

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フォームの検証は役に立ちますか?スクリプトを使用する必要はありません。 [こちら](https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Forms/Data_form_validation)を試してください。 – Doug

+0

@Doug問題は私がテストのために勉強していることです。私はこれをこのようにする必要があります。 – Gonzalo

答えて

1

それはあなたが再利用可能なisNullOrEmpty機能を作ることができる少なくとも第1 .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

のように直接ではなくyesです。 http://stackoverflow.com/a/28145281/213469 –

1

if(!height) { $("#msg").text("Height is not defined") }これはfalse、未定義、NaN、ゼロ、文字列の空の値を表します

関連する問題