how to create a form validation which states that input value shouldn't be empty and it should be > 0? - validation

I want to make a logic before submitting which states that input value shouldn't be any empty value and it should be greater than 0.
<Form className = "workout-form">
<div className ="form-row">
<label className ="form__label" value>Duration</label>
<input type = 'number' value = {duration} min = '0' onChange = {(e) => setDuration(e.target.value)} class = 'duration' placeholder="min" required/>
</div>
<button className ="form-btn" onClick = {submitWorkout}>Add Workout</button>
</Form>

A way to do it is to create a form validation function that will be called when we want to submit the form, and when the form is correctly completed, you then call the function to submit the form informations.
An example of the form control function
function formValidation(){
duration = document.getElementById('durationField').value;
if(duration > 0 && duration != ""){
//call the submit function
//submitWorkout()
}
}
//function to submit the form
function submitWorkout(){
//content of the function
}
For this to work you have to add the id property to your input field and set it to durationField as follow:
<input type = 'number' id='durationField' value = {duration} min = '0' onChange = {(e) => setDuration(e.target.value)} class = 'duration' placeholder="min" required/>

Related

how to validate 2 fields with Minimum/Maximum compare validation in ionic3?

Working on reactive form group which contain 2 fields such as min and max, data is coming form hard-coded array data . when we enter the value on respective field just want to show validation that min value should be greater than max
Hope this will help you
create a form as bellow
createForm() {
this.personalDataForm = new FormGroup({
fieldOne: new FormControl("", [Validators.minLength(5), Validators.maxLength(15)])
// ...
});
}
add validations to your template
<form [formGroup]="personalDataForm">
<ion-row>
<label class="lbl-lnu">fieldOne :</label>
<input type="text" class="input-lnu" formControlName="fieldOne">
<div class="form-control-feedback" *ngIf="personalDataForm.controls.fieldOne.errors && (personalDataForm.controls.fieldOne.dirty || personalDataForm.controls.fieldOne.touched)">
<p class="error-msg" *ngIf="personalDataForm.controls.fieldOne.errors.minlength">Minimum length is 5</p>
<p class="error-msg" *ngIf="personalDataForm.controls.fieldOne.errors.maxlength">Maximun length is 15</p>
</div>
</div>
</ion-row>
</form>
to fire validation when submit, use bellow function
function isValid(): boolean {
const valid = this.personalDataForm.valid
if (!valid) { // if not valid fire validation
Object.keys(this.personalDataForm.controls).forEach(field => {
const control = this.personalDataForm.get(field);
control.markAsTouched({ onlySelf: true });
});
}
return valid; // if form data valid return true, otherwise false
}

Unclear syntax in redux-form

Having trouble understanding the syntax in redux-form...
In redux-docs
const renderField = (field) => (
<div className="input-row">
<input {...field.input} type="text"/>
{field.meta.touched && field.meta.error &&
<span className="error">{field.meta.error}</span>}
</div> )
How is the spread operator used inside the input and why does the following returnes an error:
<input {...field.input, id} type="text"/>
The second syntax I dont understand is:
class MyCustomInput extends Component {
render() {
const { input: { value, onChange } } = this.props <---??
return (
<div>
<span>The current value is {value}.</span>
<button type="button" onClick={() => onChange(value + 1)}>Inc</button>
<button type="button" onClick={() => onChange(value - 1)}>Dec</button>
</div>
)
}
}
What is:
input: { value, onChange }
?
Queston 1:
The error from using {...field.input, id} should be something like the following:
Syntax error: ...: Unexpected token, expected }
If you already have props as an object, and you want to pass it in
JSX, you can use ... as a “spread” operator to pass the whole props
object (Spread Attributes)
So it appears the JSX attribute spread is not exactly the same as a es2015 spread. I believe it is limited to just the examples in the react docs.
Question 2:
The Field component passes these props to your wrapped component MyCustomInput
input.onChange(eventOrValue) : Function
A function to call when the form field is changed. It expects to either receive the React SyntheticEvent or the new value of the field.
input.value: any
The value of this form field. It will be a boolean for checkboxes, and a string for all other input types. If there is no value in the Redux state for this field, it will default to ''. This is to ensure that the input is controlled. If you require that the value be of another type (e.g. Date or Number), you must provide initialValues to your form with the desired type of this field.
In other words when MyCustomInput fires onChange the Field component will dispatch an action to update the form store.
The value prop is used to maintain the state MyCustomInput.

Laravel : send value of check box to controller without posting?

I'm using Laravel for my application.
I have made a PRINT button on my HTML page which is simply calling a route, to be able to send it throught DOMPDF to print it to PDF.
Print
Now, in my Controller, I would like to get the value of a radio button which has been created in the HTML this way
<div class="col-lg-7 selectie">
<input type="radio" name="factuur_selectie" id="factuur_selectie" value="1" checked> Alle facturen&nbsp
<input type="radio" name="factuur_selectie" id="factuur_selectie" value="2"> Betaalde facturen
<input type="radio" name="factuur_selectie" id="factuur_selectie" value="3"> Onbetaalde facturen
</div>
In my controller I can not find the way to get the value of the checkbox, I suppose because I'm not doing a submit ?
How would I be able to get the value of the radio button please?
public function printFacturen(Request $request){
}
I already tried three following ways, but it is not working :
$fields = Input::get('factuur_selectie');
$value = $request->get('factuur_selectie');
$request->input('factuur_selectie');
Bestregards,
Davy
You need to grab the value of factuur_selectie using JavaScript and add it to the generated URL, something like:
var val = document.querySelector('#factuur_selectie:checked').value;
var btn = document.querySelector('.btn.btn-default');
var url = btn.getAttribute('href');
btn.setAttribute('href', url + '?factuur_selectie=' + val);
Then you should be able to retrieve factuur_selectie from your controller.
Probably you are going to need to update the value everytime an option is selected. In that case you can retrieve the value from then event itself:
var btn = document.querySelector('.btn.btn-default');
document.querySelector('.selectie').addEventListener('change', function(event) {
var val = event.target.value;
var url = btn.getAttribute('href');
var pos = url.indexOf('?');
// If URL already contains parameters
if(pos >= 0) {
// Remove them
url = url.substring(0, pos);
}
btn.setAttribute('href', url + '?factuur_selectie=' + val);
});
Here you have a working example.

AngularJS Form Validation inside an ng-repeat

So I am trying to validate the input of one item inside of an ng-repeat. For examples sake lets say that I have 5 items (1,2,3,4,5) and I only want to validate the form if the 4th item is selected.
I have used ng-pattern before to validate forms, but not one that had a dropdown menu to select item.name
I have included the regex I would like the 4th item to be validated with inside the ng-pattern.
<div>
<select name="name" ng-model="item.name" ng-options="item for item in items" required></select>
</div>
<div>
<input name="results" type="text" ng-model="item.results" ng-pattern="/^\d\d\d\/\d\d\d/" required>
</div>
Any suggestions as to the correct way to validate this situation would be greatly appreciated. I have thought about creating a directive to validate this, but that feels like is an overly complicated solution to this since I would not use the directive more than once in this app.
//////////////////////////////////////////////////
It wouldn't let me answer my own question so here is the answer I figured out.
What I ended up having to do was use ng-pattern and pass it a function.
<input name="results" type="text" ng-model="vital.results" ng-pattern="vitalRegEx()" required>
Here is the controller code
$scope.item4RegEx = /^\d{2,3}\/\d{2,3}$/;
$scope.itemRegEx = function() {
if($scope.item && $scope.item.name === "fourth item")
return $scope.item4RegEx;
else return (/^$/);
};
or else...
add ng-change directive on the select dropdown which calls a Controller method and that controller method sets a flag whether to validate form or not.
eg.
<select ng-change="checkIfFormShouldbeValidated()" ng-model="item.name"></select>
// Inside controller
$scope.checkIfFromShouldBeValidated = function(){
if( $scope.item.name == 4th Item ) $scope.shouldValidate = true;
else $scope.shouldValidate = false;
};
$scope.formSubmit = function(){
if(($scope.shouldValidate && form.$valid) || (!$scope.shouldValidate)){
// Submit Form
}
};
See if it helps.
I wrote this recursive function inside my controller to check the validity of all child scopes.
function allValid(scope) {
var valid = true;
if (scope.$$childHead) {
valid = valid && allValid(scope.$$childHead);
}
if (scope.$$nextSibling) {
valid = valid && allValid(scope.$$nextSibling);
}
if (scope.scorePlannerForm) {
valid = valid && scope.myForm.$valid;
}
return valid;
}
Then in my controller I check this with the controller scope.
function formSubmit() {
if (allValid($scope)) {
// perform save
}
}

Issue with validation on Razor View in MVC

I am building wizard step demo application with MVC3 and using razor view engine as begineer level.
I came across on problem with validation when hide & show control through javascript.
Please look my code section as per below
<div class="editor-field">
#Html.EditorFor(model => model.CheckName2)
#Html.ValidationMessageFor(model => model.CheckName2)
</div>
my javascript function as per below, hide & show on some condition
// attach nextStep button handler
$("#next-step").click(function () {
var $step = $(".wizard-step:visible"); // get current step
//check if URL2 is having any content
var val = $("#URL2").val();
if (val == "") {
$("#CheckName2").hide();
//want to remove validation here
}
else {
$("#CheckName2").show();
//want to add validation here
}
var validator = $("form").validate(); // obtain validator
var anyError = false;
$step.find("input").each(function () {
if (!validator.element(this)) { // validate every input element inside this step
anyError = true;
}
});
if (anyError)
return false; // exit if any error found
How can i handle validation here?
thanks in advance.
Force validation of your form with $("#IdOfFormYouEdit").validate(); or $("#IdOfTextbox").validate(); to validate only one element.
This is possible if you have put validation attributes on your view model classes. If you don't you can add validation on an element by adding the data-val attributes. For example:
<input type="text" data-val="true" data-val-number="The field someField must be a number." data-val-required="SourceId required" />

Resources