Home >Web Front-end >JS Tutorial >JavaScript DOM Learning Chapter 8 Form Error Prompt_Basic Knowledge

JavaScript DOM Learning Chapter 8 Form Error Prompt_Basic Knowledge

WBOY
WBOYOriginal
2016-05-16 18:34:19847browse

In my opinion, warning boxes are only used when the browser does not support other methods of displaying error messages. The W3C recommends that we display error messages near form items. This is a good approach, so we only use warning dialogs when the browser does not support this advanced approach.
Example
Try the example below. Each item is required. Also I would insist if the email item has the @ symbol. If not, an error message will be prompted.

Copy code The code is as follows:

var W3CDOM = (document.getElementsByTagName && document.createElement) ;

window.onload = function () {
document.forms[0].onsubmit = function () {
return validate()
}
}

function validate() {
validForm = true;
firstError = null;
errorstring = '';
var x = document.forms[0].elements;
for (var i=0;i  if (!x[i].value)
     writeError(x[i],'This field is required');
  }
if (x['email'].value.indexOf('@') == -1)
writeError(x['email'],'This is not a valid email address');
if (!W3CDOM)
alert(errorstring);
if (firstError)
firstError.focus();
if (validForm)
alert('All data is valid!'); 🎜> return false;
}

function writeError(obj,message) {
validForm = false;
if (obj.hasError) return;
if (W3CDOM) {
        obj.className = ' error';
       obj.onchange = removeError;
      var sp = document.createElement('span'); appendChild(document.createTextNode(message));
               obj.parentNode.appendChild(sp); ' message 'n';
obj.hasError = true;
}
if (!firstError)
firstError = obj;
}

function removeError()
{
this.className = this.className.substring(0,this.className.lastIndexOf(' '));
this.parentNode.removeChild(this.hasError);
this.hasError = null ;
this.onchange = null;
}


Explanation
First we insist on whether to support W3C DOM. This example works in IE on a mac, but it's normal if it doesn't work on other pages. Because that browser does not have enough support for W3C DOM and cannot handle all situations.

Then we create the onsubmit event handler, which calls our verification function validation().




Copy code


The code is as follows: }
}


validate()
We assume that the form is verified (validForm=true), and we set firstError=null. Finally we'll give the first error element a focus. Then create a string: errorstring, which contains all error information. This is only for W3C DOM browsers.




Copy code


The code is as follows:

var x = document.forms[0].elements;
for (var i=0;i if (!x[i].value)
           writeError(x[i],'This field is required');
}
if (x['email'].value.indexOf('@') == -1)
writeError(x['email'],'This is not a valid email address');

The core of this vlidate() function is the same as usual. Check for errors in any order you want. When you find an error, call writeError() and pass it the error field and error message.

If the browser does not support W3C DOM, use errorString to generate a warning box. You may want to modify the content of the warning box.

Copy code The code is as follows:
if (!W3CDOM)
alert(errorstring) ;

For user convenience, set focus on the first error element.

Finally return validaForm. If it is still true, submit the form. If not, stop submitting.

writeError()
This function is used to output error information to the form item. If it fails, it means that the browser does not support W3C DOM, and then the error message is sent to errorstring.
This function will pass a form item and an error message.

Copy code The code is as follows:
function writeError(obj,message)
{

First we set validForm to false: this form is not filled in correctly and should not be submitted.

Copy code The code is as follows:
validForm = false;
}

Then check whether the form item already has an error message. If so, return to the validation() function. I don't want to have two error messages after the same item.

if (obj.hasError) return; Check whether the browser supports W3C DOM:

Copy code The code is as follows:
obj.className = ' error';

Then set an onchange event handler for the error form item:

Copy code The code is as follows:
obj.onchange = removeError;

Create a to contain the error message, and Set its class to "error". Set the style to be rendered in CSS.

Copy code The code is as follows:
var sp = document.createElement('span');
sp.className = 'error';

Add an error message text node to .

Copy code The code is as follows:
sp.appendChild(document.createTextNode(message));

Then add this to the corresponding form item (in this example, each form item has a

tag).

Copy code The code is as follows:
obj.parentNode.appendChild(sp);

Finally, set the hasError attribute to this form. This attribute can be used both to indicate the incorrect form item and to facilitate removal of the error message in the future.

Copy code The code is as follows:
obj.hasError = sp; 2 }
For For browsers that do not support it, we save the name of the form item and the error message in the errorstring. This string will pop up at the end. Also set the hasError attribute for him.

[code] else {
errorstring = obj.name ': ' message 'n';
obj.hasError = true;
}

If the value of validForm is still true at this time, set firstError to the current element. to facilitate setting focus in the future.

Copy code The code is as follows:
if (validForm)
firstError = obj;
removeError()

The onchange event handler of each error form item points to this function. If the user modifies the corresponding form field, we politely assume that the error has been fixed. So the error message should disappear.

First remove the error item in the form item's class. This is used to remove specific error styles.

Copy code The code is as follows:
function removeError() {
this.className = this.className.substring(0,this.className.lastIndexOf(' '));

Then remove the error message. The hasError attribute points to the that contains the information, so we remove it from the form item's parent element.

Copy code The code is as follows:
this.parentNode.removeChild(this.hasError);
Finally do some cleaning. Set the hasError property to null, and then remove the onchange event handler.

[code]this.hasError = null;
this.onchange = null;
}


Translation address: http://www.quirksmode .org/dom/error.html

Please keep the following information for reprinting
Author: Beiyu (tw:@rehawk)
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn