Implementing basic validation using the HTML Form Validation API

Let's start by implementing the getNewBookCollectionName method. Its goal is simply to return the name of the book collection that needs to be created. It will be called whenever the user asks you to create a collection:

getNewBookCollectionName(): string { 
    // build upon standard HTML DOM validation 
    if (this._newBookCollectionName.checkValidity() === false) { 
        this._newBookCollectionName.reportValidity(); 
        throw new Error("Invalid collection name!"); 
    } 
    return this._newBookCollectionName.value; 
} 

When this method executes, it first checks whether the field is currently valid or not. To do this, it relies on native HTML form validation support (https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Form_validation) and the corresponding JavaScript DOM APIs. If you look at the index.html template, you'll see that the newBookCollectionName input field has been marked as mandatory using the required attribute:

<input id="newBookCollectionName" type="text" title="Name" placeholder="Name" *required*> 

The check is done using the checkValidity() method on the DOM input node. If the input is not valid (for example, no value has been given), then the method calls reportValidity(), which will let the user know that something is wrong. Then, the method throws an Error instance to let the calling code know that something went wrong. Actually, this is not the best practice, as it actually abuses exceptions. We will explain why in the next subsection.

Finally, the method returns the value of the input field.

The following is what the user will see when there are validation issues:

This is great because we get nice-looking error messages that work in all modern web browsers without any effort.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.113.197