如何在不使用jQuery插件的情况下验证名字和姓氏

时间:2022-11-28 14:34:51

I am looking to validate the First Name and Last Name as per the Google sign-up page using jQuery. My code displays the error message once the Input box is left empty. However, how do I go about clearing the error message once the input box is filled up with some data ??

我希望使用jQuery根据Google注册页面验证名字和姓氏。输入框保留为空后,我的代码会显示错误消息。但是,如果输入框中填满了一些数据,我该如何清除错误信息?

I need to do the following things:

我需要做以下事情:

  • If both input boxes are empty, only one error message should pop-up, probably the second input box error message.

    如果两个输入框都为空,则只会弹出一条错误消息,可能是第二个输入框错误消息。

  • If the second box is non-empty, the error-message should be of first input box.

    如果第二个框非空,则错误消息应为第一个输入框。

Meanwhile, I have also pasted the equivalent Javascript code which performs the validation as good as its required.

同时,我还粘贴了等效的Javascript代码,该代码执行的验证与其要求一样好。

Could some help me how to get the same reflected in jQuery ?

有人可以帮助我如何在jQuery中反映出来吗?

HTML code:

<div class="first_container">Name</div>
    <div id ="nameBlock">
       <input type="text" name="fname" placeholder="First" id="cust_fname"/>
       <input type="text" name="lname" placeholder="Last"  id="cust_lname"/>
    </div>

 <div id="name_error_msg"> 
    <span id="spanUsernameRequired" style="visibility: hidden; font-weight:bold; color: Red;"></span>
    <span id="spanLastnameRequired" style="visibility: hidden; font-weight:bold; color: Red;"></span>
 </div>

CSS code:

.first_container {
    padding: 3px;
    width: 150px;
    font-style: italic;
    font-weight: bold;
    color: #a77;}

#nameBlock {
    display: inline-block;}

#cust_fname {
    margin: 3px;
    padding: 5px;
    width: 170px;}

#cust_lname {
    margin: 5px;
    padding: 5px;
    width: 170px;}

#name_error_msg{
    margin: 5px;
    color: red;}

jQuery code:

  $(document).ready(function() {
      var cust_fname = $('#cust_fname').val();
      var cust_lname = $('#cust_lname').val();
      var name_regex = /^[A-Za-z]+$/;

        $("input").blur(function(){
            if(cust_fname.length==0){
                $(name_error_msg).text("First name can't be empty");
                $(this).css("border-color", "red");
                return false;}

        $("input").focus(function(){
         $(name_error_msg).text("");
            if(cust_fname.length > 0) { 
                 $(":focus").$(name_error_msg).html().css("border-color", "green"); }
        });
      })
 });

Javscript code:

    function fname_validate(){  

    var x = document.getElementById("cust_fname").value;
    var regex_char = /^[A-Za-z]+$/;


    if((x == "") || (x==null)){

        document.getElementById("spanUsernameRequired").innerHTML = "<b><i>You can't leave First Name empty</b></i>";
        document.getElementById("spanUsernameRequired").style.visibility = 'visible'; 
        return false;
        }

    else if(isNaN){
        document.getElementById("spanUsernameRequired").innerHTML = "<b><i>No numbers allowed</b></i>";} 


    if(x.match(regex_char)){
        document.getElementById("spanUsernameRequired").innerHTML = "";
        document.getElementById("spanUsernameRequired").style.visibility = 'hidden';

        if((document.getElementById("cust_lname").value == "") || (document.getElementById("cust_lname").value==null)){
            document.getElementById("spanLastnameRequired").style.visibility = 'visible';
        }

        return false;}
    }


    function lname_validate(){

    var x = document.getElementById("cust_lname").value;
    var regex_char  = /^[A-Za-z]+$/;

        if(x=="" || x==null){
            document.getElementById("spanLastnameRequired").innerHTML = "<b><i>You can't leave Last Name empty</b></i>"; 
            document.getElementById("spanLastnameRequired").style.visibility = 'visible';
            /*document.getElementById("spanUsernameRequired").style.borderColor = 'red';*/
            return false;}


        else if(isNaN){
        document.getElementById("spanLastnameRequired").innerHTML = "<b><i> No numbers allowed </b></i>";
        }

        if(x.match(regex_char)){
            document.getElementById("spanLastnameRequired").innerHTML = "";
            document.getElementById("spanLastnameRequired").style.visibility = 'hidden';
            if((document.getElementById("cust_fname").value == "") || (document.getElementById("cust_fname").value==null)){
                document.getElementById("spanUsernameRequired").style.visibility = 'visible';
            }

            return true;
        }
} 

2 个解决方案

#1


My thought to validate input text fields is to use inbuilt html attributes. You can do lots of validations either using Html form or native javascript code.

我想验证输入文本字段是使用内置的html属性。您可以使用Html表单或本机JavaScript代码进行大量验证。

<input type="text" required id="firstName" pattern="[A-Z]{3}[0-9]{4}" />

You can add lot of styling using pseduo-classes with css like :valid, :invalid and :required. Using Html5, you can have custom error messages at field level. Using Html5, you can consolidate all form field errors in display at form level.

您可以使用带有css的pseduo-classes添加大量样式:valid,:invalid和:required。使用Html5,您可以在字段级别拥有自定义错误消息。使用Html5,您可以合并表单级别的所有表单字段错误。

#2


Your code is pretty messed up. E.g, isNaN is a function that takes a value as an argument, returning true if it is not fully representable as a number. ref. So

你的代码很乱。例如,isNaN是一个将值作为参数的函数,如果它不能完全表示为数字,则返回true。 REF。所以

isNaN("32") //returns false
isNaN("42.42") // returns false
isNaN("Adam43 Smith") // returns true

So, it's not really useful for your purpose since any string, as long as it has any non-number, non-decimal-point characters, will evaluate to "not a number".

因此,它对你的目的并没有用,因为任何字符串,只要它有任何非数字,非小数点字符,将评估为“不是数字”。

You also don't to create separate functions for validating fname and lname - since the majority of the code is the same, you should try to capture as much common usage as possible in a single function.

您也不需要为验证fname和lname创建单独的函数 - 因为大多数代码是相同的,您应该尝试在单个函数中捕获尽可能多的常用用法。

I haven't looked at your jQuery code or CSS, but here is a straight up JS solution that works, let me know if you have questions:

我没有看过你的jQuery代码或CSS,但这是一个直接的JS解决方案,如果你有问题请告诉我:

var fname = document.getElementById("cust_fname"),
    lname = document.getElementById("cust_lname"),
    msg = document.getElementById("name_error_msg");

function check(){
    var error = "";

    if(fname.value && lname.value){ // both fields are filled, let's validate

        //check if either value contains any numbers
        if(/[0-9]/.test(fname.value) || /[0-9]/.test(lname.value)) 
            error = "<b><i>No numbers allowed</b></i>";

        //check if either value contains any characters besides words and hyphens
        else if(!/^[A-z/-]+$/.test(fname.value) || (!/^[A-z/-]+$/.test(lname.test))) 
            error = "<b><i>No spaces or special characters allowed</b></i>";
    }
    else if(fname.value) // means lname is empty
        error = "<b><i>You can't leave Last Name empty</b></i>";
    else if(lname.value) // means fname is empty
        error = "<b><i>You can't leave First Name empty</b></i>";
    else //both are empty
        error = "<b><i>Please input your full name</b></i>";

    if(error) msg.innerHTML = error;
    else {
        msg.innerHTML = "";
        //process form
    }
}

fname.onchange = check;
lname.onchange = check;

Here's a fiddle: http://jsfiddle.net/etsnpj8n/

这是一个小提琴:http://jsfiddle.net/etsnpj8n/

#1


My thought to validate input text fields is to use inbuilt html attributes. You can do lots of validations either using Html form or native javascript code.

我想验证输入文本字段是使用内置的html属性。您可以使用Html表单或本机JavaScript代码进行大量验证。

<input type="text" required id="firstName" pattern="[A-Z]{3}[0-9]{4}" />

You can add lot of styling using pseduo-classes with css like :valid, :invalid and :required. Using Html5, you can have custom error messages at field level. Using Html5, you can consolidate all form field errors in display at form level.

您可以使用带有css的pseduo-classes添加大量样式:valid,:invalid和:required。使用Html5,您可以在字段级别拥有自定义错误消息。使用Html5,您可以合并表单级别的所有表单字段错误。

#2


Your code is pretty messed up. E.g, isNaN is a function that takes a value as an argument, returning true if it is not fully representable as a number. ref. So

你的代码很乱。例如,isNaN是一个将值作为参数的函数,如果它不能完全表示为数字,则返回true。 REF。所以

isNaN("32") //returns false
isNaN("42.42") // returns false
isNaN("Adam43 Smith") // returns true

So, it's not really useful for your purpose since any string, as long as it has any non-number, non-decimal-point characters, will evaluate to "not a number".

因此,它对你的目的并没有用,因为任何字符串,只要它有任何非数字,非小数点字符,将评估为“不是数字”。

You also don't to create separate functions for validating fname and lname - since the majority of the code is the same, you should try to capture as much common usage as possible in a single function.

您也不需要为验证fname和lname创建单独的函数 - 因为大多数代码是相同的,您应该尝试在单个函数中捕获尽可能多的常用用法。

I haven't looked at your jQuery code or CSS, but here is a straight up JS solution that works, let me know if you have questions:

我没有看过你的jQuery代码或CSS,但这是一个直接的JS解决方案,如果你有问题请告诉我:

var fname = document.getElementById("cust_fname"),
    lname = document.getElementById("cust_lname"),
    msg = document.getElementById("name_error_msg");

function check(){
    var error = "";

    if(fname.value && lname.value){ // both fields are filled, let's validate

        //check if either value contains any numbers
        if(/[0-9]/.test(fname.value) || /[0-9]/.test(lname.value)) 
            error = "<b><i>No numbers allowed</b></i>";

        //check if either value contains any characters besides words and hyphens
        else if(!/^[A-z/-]+$/.test(fname.value) || (!/^[A-z/-]+$/.test(lname.test))) 
            error = "<b><i>No spaces or special characters allowed</b></i>";
    }
    else if(fname.value) // means lname is empty
        error = "<b><i>You can't leave Last Name empty</b></i>";
    else if(lname.value) // means fname is empty
        error = "<b><i>You can't leave First Name empty</b></i>";
    else //both are empty
        error = "<b><i>Please input your full name</b></i>";

    if(error) msg.innerHTML = error;
    else {
        msg.innerHTML = "";
        //process form
    }
}

fname.onchange = check;
lname.onchange = check;

Here's a fiddle: http://jsfiddle.net/etsnpj8n/

这是一个小提琴:http://jsfiddle.net/etsnpj8n/