Question

Using Angular to design a form with 3 inputs (based on Scotch.IO tutorial for Node+Express+Angular). I would like the user to compulsorily select values for each input before submitting the form. If he doesn't, then I would like to display an error message.

<form>
    <div class="form-group">
        Start Date: <input type="date" class="form-control input-lg text-center" ng-model="formData.fromDate" placeholder="yyyy-MM-dd">
    </div>
    <div class="form-group">
        End Date: <input type="date" class="form-control input-lg text-center" ng-model="formData.toDate" placeholder="yyyy-MM-dd">
    </div>
    <div class="form-group">
        Report Type: <select class="form-control input-lg text-center" ng-model="formData.reportType">
            <option value="csv">CSV</option>
            <option value="pdf">PDF</option>
        </select>
    </div>
    <button type="submit" class="btn btn-primary btn-lg" ng-click="findStat()">Add</button>
</form>

In other words, i would not like to pass 'undefined' values back to my Node.js code. I have tried using 'required' options, which doesn't prevent undefined values from being passed back.

Was it helpful?

Solution

Give your form a name:

<form name="myForm">

Also give your inputs a name, and add validity constraints on them (required, etc.):

<input type="date" name="date" ...

Then in your findStat() function, you can access the form and check if it's valid:

$scope.findStat = function() {
    if ($scope.myForm.$invalid) {
        $scope.displayError = true;
    }
    else {
        $scope.displayError = false;
        ...
    }
}

See http://code.angularjs.org/1.2.15/docs/api/ng/directive/form and http://code.angularjs.org/1.2.15/docs/api/ng/type/form.FormController for more information.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top