validation of input text field in html using javascript

后端 未结 6 1495
鱼传尺愫
鱼传尺愫 2021-02-09 05:22


        
6条回答
  •  抹茶落季
    2021-02-09 06:04

    If you are not using jQuery then I would simply write a validation method that you can be fired when the form is submitted. The method can validate the text fields to make sure that they are not empty or the default value. The method will return a bool value and if it is false you can fire off your alert and assign classes to highlight the fields that did not pass validation.

    HTML:



    JavaScript:

    function validateForm(form) {
    
        var nameField = form.name;
        var addressLine01 = form.addressLine01;
    
        if (isNotEmpty(nameField)) {
            if(isNotEmpty(addressLine01)) {
                return true;
            {
        {
        return false;
    }
    
    function isNotEmpty(field) {
    
        var fieldData = field.value;
    
        if (fieldData.length == 0 || fieldData == "" || fieldData == fieldData) {
    
            field.className = "FieldError"; //Classs to highlight error
            alert("Please correct the errors in order to continue.");
            return false;
        } else {
    
            field.className = "FieldOk"; //Resets field back to default
            return true; //Submits form
        }
    }
    

    The validateForm method assigns the elements you want to validate and then in this case calls the isNotEmpty method to validate if the field is empty or has not been changed from the default value. it continuously calls the inNotEmpty method until it returns a value of true or if the conditional fails for that field it will return false.

    Give this a shot and let me know if it helps or if you have any questions. of course you can write additional custom methods to validate numbers only, email address, valid URL, etc.

    If you use jQuery at all I would look into trying out the jQuery Validation plug-in. I have been using it for my last few projects and it is pretty nice. Check it out if you get a chance. http://docs.jquery.com/Plugins/Validation

提交回复
热议问题