Using HTML Validation Popups with jQuery Unobtrusive Validations - html

I have an ASP.NET MVC site that uses Data Annotations for validations and I'd like to get "free" client-side validations. Most simple ones work well and Foolproof helps me with more complex scenarios. All is good so far.
However, I'd like to tie into HTML5 validations with browser support. Specifically, I want to use the little popups for all of my client-side validation messages.
I've created a JSFiddle example here explaining what I want and am coming from: https://jsfiddle.net/4nftdufu/
The behavior I want to see is shown by the first form (Foo).
<form class="form-inline">
<div class="form-group">
<input type="text" class="form-control" id="inputFoo" placeholder="Type Foo Here" required>
</div>
<button type="submit" class="btn btn-primary">Submit Foo</button>
</form>
The second form (Bar) is essentially where I'm coming from. Note that I'm hooking into some Bootstrap validation behavior here (I found that CSS online somewhere in a blog post or some other SO question). Ultimately, this is not the behavior I want and I've not spent any time cleaning up this imperfect integration.
<form class="form-inline">
<div class="form-group">
<input class="form-control input-validation-error" data-val="true" data-val-required="Required" id="inputBar" name="inputBar" placeholder="Enter Bar here" type="text" value="" aria-required="true" aria-describedby="Bar-error" aria-invalid="true">
<p class="help-block"><span class="field-validation-valid" data-valmsg-for="inputBar" data-valmsg-replace="true"></span></p>
</div>
<button type="submit" class="btn btn-primary">Submit Bar</button>
</form>
How can I get my Data Annotations + jQuery Unobtrusive-driven validations to hook into these HTML popups for all validation messages when in a supported browser?

MVC's client side validation using the jquery.validate.js and jquery.validate.unobtrusive.js files and HTML-5 validation do not play well together. The jquery.validate.js file in fact adds the novalidate attribute to your <form> element to disable HTML-5 validation using the following code
// Add novalidate tag if HTML5.
this.attr( "novalidate", "novalidate" );
If you want your messages to look like the browsers callouts, then you can always use css to style the element generated by #Html.ValidationMessageFor(). When a form control is invalid, a class="field-validation-error" is added to the element which can be used for styling (adding color, borders, using the ::after pseudo selector to add arrows etc)

Related

Weird behaviour of form element in bootstrap (gets removed from the DOM for some reason) [duplicate]

Is it possible to nest html forms like this
<form name="mainForm">
<form name="subForm">
</form>
</form>
so that both forms work? My friend is having problems with this, a part of the subForm works, while another part of it does not.
In a word, no. You can have several forms in a page but they should not be nested.
From the html5 working draft:
4.10.3 The form element
Content model:
Flow content, but with no form element descendants.
The HTML5 <input> form attribute can be the solution.
From http://www.w3schools.com/tags/att_input_form.asp:
The form attribute is new in HTML5.
Specifies which <form> element an <input> element belongs to. The value of this attribute must be the id attribute of a <form> element in the same document.
Scenario:
input_Form1_n1
input_Form2_n1
input_Form1_n2
input_Form2_n2
Implementation:
<form id="Form1" action="Action1.php" method="post"></form>
<form id="Form2" action="Action2.php" method="post"></form>
<input type="text" name="input_Form1_n1" form="Form1" />
<input type="text" name="input_Form2_n1" form="Form2" />
<input type="text" name="input_Form1_n2" form="Form1" />
<input type="text" name="input_Form2_n2" form="Form2" />
<input type="submit" name="button1" value="buttonVal1" form="Form1" />
<input type="submit" name="button2" value="buttonVal2" form="Form2" />
Here you'll find browser's compatibility.
It is possible to achieve the same result as nested forms, but without nesting them.
HTML5 introduced the form attribute. You can add the form attribute to form controls outside of a form to link them to a specific form element (by id).
https://www.impressivewebs.com/html5-form-attribute/
This way you can structure your html like this:
<form id="main-form" action="/main-action" method="post"></form>
<form id="sub-form" action="/sub-action" method="post"></form>
<div class="main-component">
<input type="text" name="main-property1" form="main-form" />
<input type="text" name="main-property2" form="main-form" />
<div class="sub-component">
<input type="text" name="sub-property1" form="sub-form" />
<input type="text" name="sub-property2" form="sub-form" />
<input type="submit" name="sub-save" value="Save" form="sub-form" />
</div>
<input type="submit" name="main-save" value="Save" form="main-form" />
</div>
The form attribute is supported by all modern browsers. IE does not support this though but IE is not a browser anymore, rather a compatibility tool, as confirmed by Microsoft itself: https://www.zdnet.com/article/microsoft-security-chief-ie-is-not-a-browser-so-stop-using-it-as-your-default/. It's about time we stop caring about making things work in IE.
https://caniuse.com/#feat=form-attribute
https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#attr-fae-form
From the html spec:
This feature allows authors to work around the lack of support for
nested form elements.
The second form will be ignored, see the snippet from WebKit for example:
bool HTMLParser::formCreateErrorCheck(Token* t, RefPtr<Node>& result)
{
// Only create a new form if we're not already inside one.
// This is consistent with other browsers' behavior.
if (!m_currentFormElement) {
m_currentFormElement = new HTMLFormElement(formTag, m_document);
result = m_currentFormElement;
pCloserCreateErrorCheck(t, result);
}
return false;
}
Plain html cannot allow you to do this. But with javascript you can be able to do that.
If you are using javascript/jquery you could classify your form elements with a class and then use serialize() to serialize only those form elements for the subset of the items you want to submit.
<form id="formid">
<input type="text" class="class1" />
<input type="text" class="class2">
</form>
Then in your javascript you could do this to serialize class1 elements
$(".class1").serialize();
For class2 you could do
$(".class2").serialize();
For the whole form
$("#formid").serialize();
or simply
$("#formid").submit();
If you're using AngularJS, any <form> tags inside your ng-app are replaced at runtime with ngForm directives that are designed to be nested.
In Angular forms can be nested. This means that the outer form is valid when all of the child forms are valid as well. However, browsers do not allow nesting of <form> elements, so Angular provides the ngForm directive which behaves identically to <form> but can be nested. This allows you to have nested forms, which is very useful when using Angular validation directives in forms that are dynamically generated using the ngRepeat directive. (source)
Another way to get around this problem, if you are using some server side scripting language that allows you to manipulate the posted data, is to declare your html form like this :
<form>
<input name="a_name"/>
<input name="a_second_name"/>
<input name="subform[another_name]"/>
<input name="subform[another_second_name]"/>
</form>
If you print the posted data (I will use PHP here), you will get an array like this :
//print_r($_POST) will output :
array(
'a_name' => 'a_name_value',
'a_second_name' => 'a_second_name_value',
'subform' => array(
'another_name' => 'a_name_value',
'another_second_name' => 'another_second_name_value',
),
);
Then you can just do something like :
$my_sub_form_data = $_POST['subform'];
unset($_POST['subform']);
Your $_POST now has only your "main form" data, and your subform data is stored in another variable you can manipulate at will.
Hope this helps!
As Craig said, no.
But, regarding your comment as to why:
It might be easier to use 1 <form> with the inputs and the "Update" button, and use copy hidden inputs with the "Submit Order" button in a another <form>.
Note you are not allowed to nest FORM elements!
http://www.w3.org/MarkUp/html3/forms.html
https://www.w3.org/TR/html4/appendix/changes.html#h-A.3.9 (html4 specification notes no changes regarding nesting forms from 3.2 to 4)
https://www.w3.org/TR/html4/appendix/changes.html#h-A.1.1.12 (html4 specification notes no changes regarding nesting forms from 4.0 to 4.1)
https://www.w3.org/TR/html5-diff/ (html5 specification notes no changes regarding nesting forms from 4 to 5)
https://www.w3.org/TR/html5/forms.html#association-of-controls-and-forms comments to "This feature allows authors to work around the lack of support for nested form elements.", but does not cite where this is specified, I think they are assuming that we should assume that it's specified in the html3 specification :)
You can also use formaction="" inside the button tag.
<button type="submit" formaction="/rmDog" method='post' id="rmDog">-</button>
This would be nested in the original form as a separate button.
A simple workaround is to use a iframe to hold the "nested" form.
Visually the form is nested but on the code side its in a separate html file altogether.
Even if you could get it to work in one browser, there's no guarantee that it would work the same in all browsers. So while you might be able to get it to work some of the time, you certainly wouldn't be able to get it to work all of the time.
While I don't present a solution to nested forms (it doesn't work reliably), I do present a workaround that works for me:
Usage scenario: A superform allowing to change N items at once. It has a "Submit All" button at the bottom. Each item wants to have its own nested form with a "Submit Item # N" button. But can't...
In this case, one can actually use a single form, and then have the name of the buttons be submit_1..submit_N and submitAll and handle it servers-side, by only looking at params ending in _1 if the name of the button was submit_1.
<form>
<div id="item1">
<input type="text" name="foo_1" value="23">
<input type="submit" name="submit_1" value="Submit Item #1">
</div>
<div id="item2">
<input type="text" name="foo_2" value="33">
<input type="submit" name="submit_2" value="Submit Item #2">
</div>
<input type="submit" name="submitAll" value="Submit All Items">
</form>
Ok, so not much of an invention, but it does the job.
Use empty form tag before your nested form
Tested and Worked on Firefox, Chrome
Not Tested on I.E.
<form name="mainForm" action="mainAction">
<form></form>
<form name="subForm" action="subAction">
</form>
</form>
EDIT by #adusza: As the commenters pointed out, the above code does not result in nested forms. However, if you add div elements like below, you will have subForm inside mainForm, and the first blank form will be removed.
<form name="mainForm" action="mainAction">
<div>
<form></form>
<form name="subForm" action="subAction">
</form>
</div>
</form>
Although the question is pretty old and I agree with the #everyone that nesting of form is not allowed in HTML
But this something all might want to see this
where you can hack(I'm calling it a hack since I'm sure this ain't legitimate) html to allow browser to have nested form
<form id="form_one" action="http://apple.com">
<div>
<div>
<form id="form_two" action="/">
<!-- DUMMY FORM TO ALLOW BROWSER TO ACCEPT NESTED FORM -->
</form>
</div>
<br/>
<div>
<form id="form_three" action="http://www.linuxtopia.org/">
<input type='submit' value='LINUX TOPIA'/>
</form>
</div>
<br/>
<div>
<form id="form_four" action="http://bing.com">
<input type='submit' value='BING'/>
</form>
</div>
<br/>
<input type='submit' value='Apple'/>
</div>
</form>
JS FIDDLE LINK
http://jsfiddle.net/nzkEw/10/
About nesting forms: I spent 10 years one afternoon trying to debug an ajax script.
my previous answer/example didn't account for the html markup, sorry.
<form id='form_1' et al>
<input stuff>
<submit onClick='ajaxFunction(That_Puts_form_2_In_The_ajaxContainer)'>
<td id='ajaxContainer'></td>
</form>
form_2 constantly failed saying invalid form_2.
When I moved the ajaxContainer that produced form_2 <i>outside</i> of form_1, I was back in business. It the answer the question as to why one might nest forms. I mean, really, what's the ID for if not to define which form is to be used? There must be a better, slicker work around.
No you cannot have a nested form. Instead you can open up a Modal that contains form and perform Ajax form submit.
Really not possible...
I couldn't nest form tags...
However I used this code:
<form>
OTHER FORM STUFF
<div novalidate role="form" method="post" id="fake_form_id_0" data-url="YOUR_POST_URL">
THIS FORM STUFF
</div>
</form>
with {% csrf_token %} and stuff
and applied some JS
var url = $(form_id).attr("data-url");
$.ajax({
url: url,
"type": "POST",
"data": {
'csrfmiddlewaretoken': '{{ csrf_token }}',
'custom-param-attachment': 'value'
},
success: function (e, data) {
if (e.is_valid) {
DO STUFF
}
}
});
Today, I also got stuck in same issue, and resolve the issue I have added a user control and
on this control I use this code
<div class="divformTagEx">
</div>
<asp:Literal runat="server" ID="litFormTag" Visible="false">
'<div> <form style="margin-bottom: 3;" action="http://login.php" method="post" name="testformtag"></form> </div>'</asp:Literal>
and on PreRenderComplete event of the page call this method
private void InitializeJavaScript()
{
var script = new StringBuilder();
script.Append("$(document).ready(function () {");
script.Append("$('.divformTagEx').append( ");
script.Append(litFormTag.Text);
script.Append(" )");
script.Append(" });");
ScriptManager.RegisterStartupScript(this, GetType(), "nestedFormTagEx", script.ToString(), true);
}
I believe this will help.
Before I knew I wasn't supposed to do this I had nested forms for the purpose of having multiple submit buttons. Ran that way for 18 months, thousands of signup transactions, no one called us about any difficulties.
Nested forms gave me an ID to parse for the correct action to take. Didn't break 'til I tried to attach a field to one of the buttons and Validate complained. Wasn't a big deal to untangle it--I used an explicit stringify on the outer form so it didn't matter the submit and form didn't match. Yeah, yeah, should've taken the buttons from a submit to an onclick.
Point is there are circumstances where it's not entirely broken. But "not entirely broken" is perhaps too low a standard to shoot for :-)
[see thecode.. code format below ]2simple trick
simply dont use other inside another form tag, please use the same elements without using form tag.
see example below
"" dont use another form // just recall the enter image description hereelement in it""

Formaction attribute is not working when input text has required attribute

I have this code, I use formaction attribute to return in home.html
but it's not working because of required attribute.
<form action="post">
Name:
<input type="text" name="name" required>
<br>
Email:
<input type="email" name="name" required>
<button name="Send" id="send">Send</button>
<button name="Return" id="return" formaction="home.html">Return</button>
</form>
The formaction attribute working fine. I can use the Network tab in my browser's developer tools to observe that when I click Return (in the live demo in your question) the form is submitted to home.html.
The required fields are still required (so I have to fill them in before that happens), but that is to be expected.
It sounds like your goal is to provide an exception and not need the user to enter any data when submitting the form to Return.
That isn't possible without adding a bunch of JS but you're approaching the problem from the wrong angle in the first place.
It looks like you want something for the user to click on that will abort filling in the form and just go to a different URL. There's no data submission involved.
That isn't a job for a submit button.
Use a link instead.
Return
You can apply CSS if you want it to look like a button, but I wouldn't recommend it. The visual appearance of the button implies that the form data will be sent somewhere, and that isn't what you are doing.
You should refer to homepage at the form tag
<form action="home.html" method="POST">
and for the submit
<input type="button" name="Return" id="return">

Angular 4 enable HTML5 validation

I want to use HTML5 validation in Angular 4 rather than their form's based validation/reactive validation. I want to keep the validation running in the browser.
It used to work in Angular 2, but since I've upgraded, I can't get even manually created forms without any angular directives to validate using HTML5.
For instance, this won't validate in the browser at all:
<form>
<h2>Phone Number Validation</h2>
<label for="phonenum">Phone Number (format: xxxx-xxx-xxxx):</label><br />
<input id="phonenum" type="tel" pattern="^\d{4}-\d{3}-\d{4}$" required>
<input type="submit" value="Submit">
</form>
Angular4 automatically adds a novalidate attribute to forms.
To override this, you can add the ngNativeValidate directive to the form.
<form ngNativeValidate>
<h2>Phone Number Validation</h2>
<label for="phonenum">Phone Number (format: xxxx-xxx-xxxx):</label><br />
<input id="phonenum" type="tel" pattern="^\d{4}-\d{3}-\d{4}$" required>
<input type="submit" value="Submit">
</form>
Unfortunately I do not see this reflected in the docs yet, but found it by looking at the source code:
https://github.com/angular/angular/blob/master/packages/forms/src/directives/ng_no_validate_directive.ts
It appears also adding ngNoForm to the form has the same effect as ngNativeValidate depending on your use-cases for needing to declare something as not a form for whatever reason.
Hope this helps.
use ngNoForm or ngNativeValidate in your form
<form ngNoForm/ngNativeValidate>
...
</form>

How to validate a Classic ASP form with AngularJS

Is it possible to get AngularJS working with Classic ASP? I couldn't find any resources on this, but I suspect the answer would be yes, since AngularJS (excluding its AJAX stuff) is mostly Client Side.
If that is the case, I have a form that looks like this:
How can I use AngularJS to validate this form? The validation I want is:
All Fields Required
Email must be valid format
I know I can use jQuery, but I want to do this with AngularJS. I have already gone ahead and added the AngularJS script to the bottom of the form, also added the ng-app to the <html tag.
I'd like to know the proper, decoupled way of doing this, also if possible, client side end to end test for this simple form, just so that I get the idea.
UPDATE: Thanks to DoubleSharp's link, I have progressed a little, though validation still does not work.
Here is the code I have:
<div class="panel-body" ng-controller="UserCtrl">
<form novalidate class="css-form">
<div class="form-group">
<input type="text" placeholder="First Name" class="form-control" ng-model="user.fname" required />
</div>
<div class="form-group">
<input type="text" placeholder="Last Name" class="form-control" ng-model="user.lname" required />
</div>
<div class="form-group">
<input type="text" placeholder="Email" class="form-control" ng-model="user.email" required />
</div>
<div class="form-group">
<input type="text" placeholder="Password" class="form-control" ng-model="user.password" required />
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
And here is my JavaScript/Angular Code:
function UserCtrl($scope) {
$scope.master= {};
$scope.update = function(user) {
$scope.master = angular.copy(user);
};
$scope.reset = function() {
$scope.user = angular.copy($scope.master);
};
$scope.reset();
}
As you can see I simply copying the tutorial, I have also gone ahead and added the CSS styles, but my validation is still not working, even though the page is freshly loaded, I get ng-pristine ng-invalid ng-invalid-required CSS on my text fields, whereas in the tutorial they have ng-valid
I am guessing this has something to do with ngModel which I have no where, but the tutorial does not mention that at all in its code, I'm confused.
If you just want to validate that the required fields are entered and that the email is in a valid format, it can all be done client side without any calls back to the server, so it doesn't matter if it is ASP classic, PHP, etc... it is all in the browser. The AngularJS site has examples of this, so rather than repeating them here...
See this page for implementing custom form validation: http://docs.angularjs.org/guide/forms
See this page for the email input type: http://docs.angularjs.org/api/ng.directive:input.email

CSS - Focus login fields just like twitter with only CSS?

I already posted a similar question and got a jQuery solution that works. Now I want to do it with only CSS/HTML. I saved twitter's homepage locally and deleted all the js scripts and noticed that the effect I'm trying to achieve is with CSS/HTML (when you click on the username/pass the values "Username"/"Password" stay there until you enter text).
I'm a newbie at these kind of new CSS/HTML effects and have spent the last couple of hours trying to replicate it with no success.
Here's the html of twitter's login form:
<form action="#" class="signin" method="post">
<fieldset class="textbox">
<div class="holding username">
<input type="text" id="username" value="" name="session[username_or_email]" title="Username or email" autocomplete="on">
<span class="holder">Username</span>
</div>
<div class="holding password">
<input type="password" id="password" value="" name="session[password]" title="Password">
<span class="holder">Password</span>
</div>
</fieldset>
<fieldset class="subchck">
<label class="remember">
<input type="checkbox" value="1" name="remember_me">
<span>Remember me</span>
</label>
<button type="submit" class="submit button">Sign in</button>
</fieldset>
I've looked over the site's CSS but it's 10,000 lines and very complicated. How should the CSS look like? Or could you point me out to a tutorial on how to achieve the same effect as this is driving me nuts?
Thank you very much,
Cris
Set the HTML autofocus attribute:
<input type="text" placeholder="Type here ..." autofocus="autofocus" />
You can target elements that are focused or blured like so:
input:focus {color:red;}
You now need to nest the CSS to hide the span called holder inside the input.
span.holder input:focus {visibility:hidden;}
I have not tried this, but it would be something like this.
To clarify, I have just pulled the JavaScript twitter use and the source for their home page and I can confirm that they are using the following JavaScript function for focus on the field
inp.focus()
The JavaScript is quite lengthy but it looks like after a quick read that they are using jQuery that is setting focus based on the class being username.
I just looked at the autofocus property suggested by another poster and this method has worked for me in my web app currently under development.
The code for this is
<input type="text" id="username" value="" name="session[username_or_email]" title="Username or email" autocomplete="on" autofocus>
Note, per the documentation at the W3C website, the autofocus property can only be used once on the page. I have put it into a form that is hidden and shown in an inline element using Fancybox.
The grayed out text in the input field can be done with the place-holder element, something I'm already using, add the following into your input element
placeholder="Username"
NOTE: Both placeholder and autofocus are HTML5 properties and may not be supported by all major browsers yet, this is why JavaScript is still being used by sites like twitter.
The styling is done based on CSS/CSS3 greatly, an excellent resource is W3Schools. I would recommend for what you're wanting to achieve start at the CSS3 section looking at borders.
Another resource that is excellent but hasn't been updated for about a month and a half sadly is doctype.tv. Nick has some fantastic advise regarding styling your website along with some great insight into design.
Judging by the bolded text in your question (when you click on the username/pass the values "Username"/"Password" stay there until you enter text), I'm guessing what you want is the placeholder attribute, which #phihag has in his example.
<input type="text" placeholder="This text will disappear" />
The placeholder attribute works without Javascript in browsers that support it. For older browsers, you'll need some Javascript, and this is probably what Twitter is doing in their code.
See the Wufoo page on the Placeholder Attribute for more details, including how to do a javascript fallback and what browsers it is currently supported in.
See also this demo which shows how to style the ":placeholder" and ":active" states (at least for webkit and mozilla).