By Maninblack


2014-04-24 06:23:21 8 Comments

I have tried following code for make the required field to notify the required field but its not working in safari browser. Code:

 <form action="" method="POST">
        <input  required />Your name:
        <br />
        <input type="submit" />
    </form>

Above the code work in firefox. http://jsfiddle.net/X8UXQ/179/

Can you let me know the javascript code or any workarround? am new in javascript

Thanks

10 comments

@mikiqex 2014-04-24 06:26:49

Safari, up to version 10.1 from Mar 26, 2017, doesn't support this attribute, you need to use JavaScript.

This page contains a hacky solution, that should add the desired functionality: http://www.html5rocks.com/en/tutorials/forms/constraintvalidation/#toc-safari

HTML:

<form action="" method="post" id="formID">
    <label>Your name: <input required></label><br>
    <label>Your age: <input required></label><br>
    <input type="submit">
</form>

JavaScript:

var form = document.getElementById('formID'); // form has to have ID: <form id="formID">
form.noValidate = true;
form.addEventListener('submit', function(event) { // listen for form submitting
        if (!event.target.checkValidity()) {
            event.preventDefault(); // dismiss the default functionality
            alert('Please, fill the form'); // error message
        }
    }, false);

You can replace the alert with some kind of less ugly warning, like show a DIV with error message:

document.getElementById('errorMessageDiv').classList.remove("hidden");

and in CSS:

.hidden {
    display: none;
}

and in HTML:

<div id="errorMessageDiv" class="hidden">Please, fill the form.</div>

The only drawback to this approach is it doesn't handle the exact input that needs to be filled. It would require a loop accross all inputs in the form and checking the value (and better, check for "required" attribute presence).

The loop may look like this:

var elems = form.querySelectorAll("input,textarea,select");
for (var i = 0; i < elems.length; i++) {
    if (elems[i].required && elems[i].value.length === 0) {
        alert('Please, fill the form'); // error message
        break; // show error message only once
    }
}

@Maninblack 2014-04-24 06:37:25

Java Script Code please..

@Maninblack 2014-04-24 07:26:07

Can you replace above the code in jsfiddle.net/X8UXQ/179 because I have tried that code also so only.

@mikiqex 2014-04-24 07:54:58

I don't think I can, unless you share it somehow (sorry, never tried). Anyway, I updated my answer with HTML code, that worked for me in the JSFiddle.

@Maninblack 2014-04-24 08:24:35

Send me that link.. if you updated means that link would be cahnge so please share that.

@mikiqex 2014-04-24 08:33:43

No, but I created a new Fiddle for you: jsfiddle.net/mikiqex/US4sr

@Maninblack 2014-04-24 08:54:32

Thank you so much but its showing alert so how to show below the text filed(like this : html5rocks.com/en/tutorials/forms/constraintvalidation/…)

@mikiqex 2014-04-24 09:33:28

Updated. To look like the browser's message it would require much more styling and I find such bubbles quite tricky to do.

@Maninblack 2014-04-24 09:38:43

HI can you let me know the code.. if updated means , send me the link. I am new thats why.

@mikiqex 2014-04-24 09:47:23

The same link as before, I updated the Fiddle: jsfiddle.net/mikiqex/US4sr/8. But to be honest, I think this isn't a good way to start with JS. I'm trying to lead you, but you probably need a complete solution instead (which I'm not able to make for you).

@Maninblack 2014-04-24 10:03:19

Sure can you let me know your skype id?

@mikiqex 2014-04-24 10:22:57

Sorry, I use Skype for business related stuff only. According to text of your original question I consider it answered. There's nothing more I can do for you in this matter.

@Maninblack 2014-04-24 10:28:17

Thanks for you help

@mikiqex 2014-04-24 10:36:34

I love how you accepted my answer for somebody else :-P

@Maninblack 2014-04-24 15:36:09

happy: I have accepted your answer... ok please help for buble error.. update in fiddle and let me know please

@mikiqex 2014-04-24 17:40:00

Well, it's more "appreciated", than happy. I posted my solution in your other question as well, If you like it, feel free to accept it as well ;-) I don't think I can make it any better, I did my best.

@Syed Shibli 2018-07-02 06:56:12

function customValidate(){
    var flag=true;
    var fields = $('#frm-add').find('[required]');  //get required field by form_ID

    for (var i=0; i< fields.length;i++){
      debugger
      if ($(fields[i]).val()==''){
        flag = false;
        $(fields[i]).focus();
      }
    }
    return flag;
  }


if (customValidate()){
// do yor work
 }

@fernanDOTdo 2017-03-28 21:08:45

The new Safari 10.1 released Mar 26, 2017, now supports the "required" attribute.

http://caniuse.com/#search=required

@dewd 2018-07-25 12:12:54

such a joke it's taken so long. just when you think all the IE8 problems have gone...

@Leslie 2017-03-27 19:38:31

Within each() function I found all DOM element of text input in the old version of PC Safari, I think this code useful for newer versions on MAC using inputobj['prpertyname'] object to get all properties and values:

    $('form').find("[required]").each(function(index, inputobj) {
        if (inputobj['required'] == true) { // check all required fields within the form
            currentValue = $(this).val();
            if (currentValue.length == 0) {
                // $.each((inputobj), function(input, obj) { alert(input + ' - ' + obj); }); // uncomment this row to alert names and values of DOM object
                var currentName = inputobj['placeholder']; // use for alerts
                return false // here is an empty input
            }
        }
    });

@Juliomac 2016-09-04 17:23:09

I have built a solution on top of @Roni 's one.

It seems Webshim is deprecating as it won't be compatible with jquery 3.0.

It is important to understand that Safari does validate the required attribute. The difference is what it does with it. Instead of blocking the submission and show up an error message tooltip next to the input, it simply let the form flow continues.

That being said, the checkValidity() is implemented in Safari and does returns us false if a required filed is not fulfilled.

So, in order to "fix it" and also show an error message with minimal intervention (no extra Div's for holding error messages) and no extra library (except jQuery, but I am sure it can be done in plain javascript)., I got this little hack using the placeholder to show standard error messages.

$("form").submit(function(e) {

  if (!e.target.checkValidity()) {
    console.log("I am Safari"); // Safari continues with form regardless of checkValidity being false
    e.preventDefault(); // dismiss the default functionality

    $('#yourFormId :input:visible[required="required"]').each(function () {
      if (!this.validity.valid) {
        $(this).focus();
        $(this).attr("placeholder", this.validationMessage).addClass('placeholderError');
        $(this).val(''); // clear value so it shows error message on Placeholder.
        return false;
      }
    });
    return; // its invalid, don't continue with submission
  }

  e.preventDefault(); // have to add it again as Chrome, Firefox will never see above
}

@Matthias Bohlen 2016-10-01 12:01:02

You can add this event handler to your form:

// Chrome and Firefox will not submit invalid forms
// so this code is for other browsers only (e.g. Safari). 
form.addEventListener('submit', function(event) {
    if (!event.target.checkValidity()) {
        event.preventDefault();
        var inputFields = form.querySelectorAll('input');
        for (i=0; i < inputFields.length; i++) {
            if (!inputFields[i].validity.valid) {
                inputFields[i].focus(); // set cursor to first invalid input field
                return false;
            }
        }
    }
}, false);

@Bryce 2016-08-12 18:33:46

I found a great blog entry with a solution to this problem. It solves it in a way that I am more comfortable with and gives a better user experience than the other suggestions here. It will change the background color of the fields to denote if the input is valid or not.

CSS:

/* .invalid class prevents CSS from automatically applying */
.invalid input:required:invalid {
    background: #BE4C54;
}
.invalid textarea:required:invalid {
    background: #BE4C54;
}
.invalid select:required:invalid {
    background: #BE4C54;
}
/* Mark valid inputs during .invalid state */
.invalid input:required:valid {
    background: #17D654 ;
}
.invalid textarea:required:valid {
    background: #17D654 ;
}
.invalid select:required:valid {
    background: #17D654 ;
}

JS:

$(function () {
    if (hasHtml5Validation()) {
        $('.validate-form').submit(function (e) {
            if (!this.checkValidity()) {
                // Prevent default stops form from firing
                e.preventDefault();
                $(this).addClass('invalid');
                $('#status').html('invalid');
            }
            else {
                $(this).removeClass('invalid');
                $('#status').html('submitted');
            }
        });
    }
});

function hasHtml5Validation () {
    return typeof document.createElement('input').checkValidity === 'function';
}

Credit: http://blueashes.com/2013/web-development/html5-form-validation-fallback/

(Note: I did extend the CSS from the post to cover textarea and select fields)

@Jim Jones 2017-02-11 02:22:24

Awesome your solution provided me with exactly what I needed. Thanks for the link as well

@tommygun 2016-02-24 10:47:41

I had the same problem with Safari and I can only beg you all to take a look at Webshim!

I found the solutions for this question and for this one very very useful, but if you want to "simulate" the native HTML5 input validation for Safari, Webshim saves you a lot of time.

Webshim delivers some "upgrades" for Safari and helps it to handle things like the HMTL5 datepicker or the form validation. It's not just easy to implement but also looks good enough to just use it right away.

Also useful answer on SO for initial set up for webshim here! Copy of the linked post:

At this time, Safari doesn't support the "required" input attribute. http://caniuse.com/#search=required

To use the 'required' attribute on Safari, You can use 'webshim'

1 - Download webshim

2 - Put this code :

<head>
    <script src="js/jquery.js"></script>
    <script src="js-webshim/minified/polyfiller.js"></script>
    <script> 
        webshim.activeLang('en');
        webshims.polyfill('forms');
        webshims.cfg.no$Switch = true;
    </script>
</head>

@Shakeel Ahmed 2016-03-29 08:27:47

Perfect and easy solution... Well done.

@tommygun 2016-03-29 08:31:52

Thank you, I added the content of the linked post so one does not need to navigate there (but still you should give the man some credit!) :)

@Shakeel Ahmed 2016-03-29 16:13:57

What does this line do? webshims.cfg.no$Switch = true;

@tommygun 2016-03-30 14:08:44

Unfortunately I can't figure it out. I also did not use it on my project, only went for the polyfill function (still this did not prevent me from pasting the code from the answer which helped me solving my problem). Let me ask the original poster of the code what this means; I will update my answer!

@Shakeel Ahmed 2016-03-31 07:53:54

Thank you very much...

@Elliott Post 2016-10-03 22:23:57

This solution is no longer valid for jQuery 3.x+

@jamogon 2015-10-16 12:06:23

I use this solution and works fine

$('#idForm').click(function(e) {
    e.preventDefault();
    var sendModalForm = true;
    $('[required]').each(function() {
        if ($(this).val() == '') {
            sendModalForm = false;
            alert("Required field should not be blank."); // or $('.error-message').show();
        }
    });

    if (sendModalForm) {
        $('#idForm').submit();
    }
});

@Roni 2015-07-09 13:51:47

If you go with jQuery then below code is much better. Just put this code bottom of the jquery.min.js file and it works for each and every form.

Just put this code on your common .js file and embed after this file jquery.js or jquery.min.js

$("form").submit(function(e) {

    var ref = $(this).find("[required]");

    $(ref).each(function(){
        if ( $(this).val() == '' )
        {
            alert("Required field should not be blank.");

            $(this).focus();

            e.preventDefault();
            return false;
        }
    });  return true;
});

This code work with those browser which does not support required (html5) attribute

Have a nice coding day friends.

@Boomerange 2016-09-27 08:27:34

This is exactly what I wanted. I have a simple field in modal so I needed simple answer (solution) for Safari. Thank you.

@Roni 2016-09-28 07:15:21

its my pleasure mate..

@brianlasta 2016-10-02 09:14:34

Try this code and BAM, problem solved. You're the best. Thank you.

@Jules Matthews 2016-10-13 22:32:41

Great stuff. This code solved my problem.

@Gokul M 2016-10-17 14:15:01

Nice answer. Thanks.

Related Questions

Sponsored Content

19 Answered Questions

[SOLVED] Storing Objects in HTML5 localStorage

24 Answered Questions

[SOLVED] How do I style a <select> dropdown with only CSS?

12 Answered Questions

38 Answered Questions

[SOLVED] How to align checkboxes and their labels consistently cross-browsers

19 Answered Questions

[SOLVED] Frame Buster Buster ... buster code needed

10 Answered Questions

[SOLVED] Using the HTML5 "required" attribute for a group of checkboxes?

9 Answered Questions

[SOLVED] How to send FormData objects with Ajax-requests in jQuery?

9 Answered Questions

5 Answered Questions

[SOLVED] No line-break after a hyphen

1 Answered Questions

Sponsored Content