Novice 2910
Novice 2910

Reputation: 1

Why doesnt required work to validate my forms?

I am trying to validate some text-fields using the required keyword, yet nothing is working?

How do I create validation using the required keyword.

Here is my code:

<div id="Name" class="tabcontent">

    <form>
        <div class="nameDiv">
              Title: <input type="text" name="Title" title="Title" id="TitleTransfer">
        </div>
        <br>
        <div class="addressDiv">
              Name: <input type="text" name="name" id="NameTransfer" required />
            <span class="asterisk"></span>
        </div>
        <br>
        <div class="emailDiv">
              Surname:
            <input type="text" name="surname" id="LastNameTransfer" required />
            <span class="asterisk"></span>
        </div>
        <br>
        <div class="numberDiv">
              Email Address:
            <input type="text" name="email Address" id="EmailTransfer" required />
            <span class="asterisk"></span>
        </div>
        <br>
        <div class="numberDiv">
              Phone number:
            <input type="text" name="Phone number" id="NumberTransfer">
        </div>
        <button  id="save-btnOne" onclick="moveContentOne()">Save</button>
    </form>
</div>

Upvotes: 0

Views: 48

Answers (2)

Kalyan
Kalyan

Reputation: 307

function validateForm() {
    var x = document.forms["myForm"]["fname"].value;
    if (x == "") {
        alert("Name must be filled out");
        return false;
    }
 }

Use this type of validation. This works for

<form name="myForm" onsubmit="validateForm()">
    <input type="text" name="fname" />
</form>

Some browsers do not support required field. Change the code to your need. I hope it helps you.

Upvotes: 0

nhlm
nhlm

Reputation: 53

the required attributes tells the browser that the form field must contain something, this is a weak validation and can be supressed when hooking the form submit through javascript (keep in mind that you do not have delivered any kind of javascript source here that might be in the orbit of the form).

I assume that the moveContentOne() hooking the onclick-event is the only javascript attached. Considering this the onSubmit-event remains untouched and will be also fired alongside of your onClick intervention. You should prefer to hook onSubmit for forms of that kind to apply custom validation, but that might detach the browser's default behavior for form validation (including the required-attachment to fields).

You might take a look at this guide: Form data validation

Upvotes: 1

Related Questions