mvc 3 razor cannot clear form value with validation class - javascript

I'm using MVC 3 with Razor and using unobtrusive client validation. Things are working great, but I want to be able to reset the form if a user decides he wants to start over or cancel his action. It seems that there is a lot of meta data attached to each form element when using the validation.
<input type="text" value="" name="User.FirstName" id="User_FirstName" data-val-required="The First Name field is required." data-val-length-max="50" data-val-length="The field FirstName must be a string with a maximum length of 50." data-val="true" class="text-box single-line">
The jQuery snippet here shows my problem. When you try to manually reset the value of the text field, some other javascript is intercepting execution after I clear the value and it sets it back to what it was:
$("#btnReset").click(function () {
alert($("#User_FirstName").val());
$("#User_FirstName").val("");
alert($("#User_FirstName").val());
});
I'm looking for pointers here on how to clear form values when a user clicks a button. It seems like such a simple task, but I can find no documentation how to accomplish this and I haven't found anything here or elsewhere to help.

I was using an html input of type reset rather than the button type. The reset should not have been used in this case.

Related

Preventing users from entering non-digits in input text field with HTML5

I have an input field of type text. Users should only be allowed to enter digits in the field. If they attempt to enter a non-digit, like a character, it should be ignored and not display in the field ( and not submitted to the server). I thought I could achieve this with the HTML5 pattern attribute:
<input class="form-control" data-remote="true" data-url="/contacts" data-method="put" pattern="^[0-9]*$" type="text" value="123456" name="contact[phone]" id="contact_phone">
But it doesn't work as expected. I can still enter any character into the field. There is no form submit button here. As soon as they tab out of field, the ajax call is made.
How can I achieve what I want with html5?
So you can totally do that by adding type="number" to your input field, It'll work in most browsers.
I'd recommend using sort of regex and a bit of JS to evaluate the input and then replace the input with permitted characters.
var phone_input = document.getElementById('contact_phone');
function validDigits(n){
return n.replace(/[^0-9]+/g, '');
}
phone_input.addEventListener('keyup', function(){
var field = phone_input.value;
phone_input.value = validDigits(field);
});
Here's a quick codepen
I'd also put a bit of validation on the model, just in case someone bypasses the JS.
I think it won't work with plain html5 since the pattern goes into affect after you submitted the form (It will make validation fail). But since you are already using js, you can just do it with for example the jQuery.keypress() function.

Angular ng-model with required

I'm trying to create a simple input with html5 "required". I'm using placeholder, so I'd like the initial value of the input to be empty. I have the input bound to a ng-model that is initialized as empty (so the placeholder shows).
When I go to the page, it shows that input is required for the , which shouldn't show unless the user submits the form and the input is empty.
how can I do this:
<input type="text" required ng-model="name">
..in controller:
$scope.name = "";
and not have the form think I am submitting an empty input?
One way of only validating when the user has actually interacted with your input element is to use $dirty to determine wether to show your error message. e.g.
<span ng-show="form.name.$dirty && form.name.$error.required">
Name is required
</span>
I just created an example of form validation regarding to your question
This should be working:
http://plnkr.co/edit/6PTNg3atPHAjL0XFtvWj?p=preview

JQuery fill the form but failed to be recognized

I am using Flask as the backend. And I wrote a simple form with WTForm, say,
field = StringField('input:', validators=[Required()])
And I write a JQuery to fill it automatically
$('#theidofthefield').val('fillingin');
And I click the submit button in the form but it shows that the field is empty. And I check the request.form.field.data is also empty.
Hope to get a solution.
I have no idea about WTForm but you can check if your field element has got the name attribute, which is required to send back to the backend code.
Your field has to be something like this:
<input type="text" name="thenameofthefield" id="theidofthefield" />
//-----------------^^^^^^^^^^^^^^^^^^^^^^^---name attribute is required.
Another way to fill value is:
$('#theidofthefield').attr('value','filling');
Lets see if it works..
In case variable field is pointer to the object then..
$(field).val('dfsdf') or $(field).attr('value','filling') may work.

Angular Validation to show all errors on submit

I have a simple example form that will validate a name to be required and 3 letters at least. Nicely display errors as you make the field dirty:
[http://plnkr.co/edit/FEclhN?p=preview]
Our designer wants , however, all the fields that are empty and that are "required" to go "red" as well, when the user presses the Submit button. Right now, unless they have touched and made the field "dirty" the validation doesn't turn the field red.
Of course the field should not be red to start with, only after they Submit the form or they make a field dirty.
jQueryValidate.org does this, so that's what they want in Angular too.
I ran into this same requirement and solved it by adding a boolean onto my controller's scope to indicate if the form had been submitted formSubmitted
And inside my form submit method I would set the value of formSubmitted to true
Then I would dynamically add a class where I needed:
<div ng-class="{'required-error': formSubmitted && formName.field.$error.required}">
<input name="field" required/>
</div>
You can also use this
https://github.com/AngularAgility/AngularAgility
For all controls and error summary in toster.
Its best way to validate and focus on field which causes validation.

Activation of the HTML5 Pattern Attribute with websockets

As a total newbie to web-based programming, I'm having trouble understanding why the pattern attribute field below fails to check the validity of the text field due to my javascript.
<form id="aForm">
<input type="text" pattern="^[ a-zA-Z0-9,#.-]+$" id="address" title="Standard address"/>
<input type="submit" id="open" value="Start"/>
</form>
The form contents are then sent to a javascript file which then sends it to the server via a websocket as in the code fragment below. However it ignores validating the form through the pattern attribute.
$(document).ready(function() {
$("#open").click(function(evt) {
evt.preventDefault();
var form = $('#aForm').serialize();
webSocket = new WebSocket("ws://localhost:9999/mh");
webSocket.onopen = function()
{
webSocket.send(form);
};
REST OF CODE....
It seems that for some reason this prevents the text from being checked before it's sent. I would like to know why and how to ensure that the form is validated by the pattern attribute.
Thanks
The HTML5 form validation is only performed when you're trying to actually submit the form, or when you explicitly use JavaScript to validate it1.
Since your JavaScript is bound to a different event (button click), form validation is not performed at that point. You can solve this by:
binding your submission to the form's submit event instead of button click, or
using the form validation API at the very beginning of your script.
I strongly recommend the first option. It makes more semantic sense and works right when the form is submitted though other methods (I don't remember if the button click will be simulated when someone presses Enter in the text field, and it definitely won't be triggered if JavaScript calls $('#aForm').submit() programmatically...).
1 At least, those are the only places I noticed - it's possible there are other events/circumstances when validation is done as well.

Categories

Resources